package com.gusto.engine.spring.parsers;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;

import com.gusto.engine.semsim.measures.impl.MatrixSimilarity;
import com.gusto.engine.semsim.measures.impl.MatrixSimilarityEntry;

public class ParserMatrixSimilarity extends AbstractBeanDefinitionParser {
	
	@SuppressWarnings("unchecked")
	protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
		BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(MatrixSimilarity.class);
		
		if (element.hasAttribute("prefix")) {
			String prefix = element.getAttribute("prefix");
			beanDefinitionBuilder.addPropertyValue("prefix", prefix);
		}
		// Should be before 'file' assignation 
		if (element.hasAttribute("fileSeparator")) {
			String fileSeparator = element.getAttribute("fileSeparator");
			beanDefinitionBuilder.addPropertyValue("entriesFileSeparator", fileSeparator);
		}
		if (element.hasAttribute("file")) {
			String file = element.getAttribute("file");
			beanDefinitionBuilder.addPropertyValue("entriesFile", file);
		}
		
		
		Element stopWords = DomUtils.getChildElementByTagName(element, "stopwords");
		if (stopWords != null) {
			List childElements = DomUtils.getChildElementsByTagName(stopWords, "stopword");
			List<String> sw = new ArrayList<String>(); 
			for (int i = 0; i < childElements.size(); ++i) {
				Element childElement = (Element) childElements.get(i);
				sw.add(childElement.getTextContent());
			}
			beanDefinitionBuilder.addPropertyValue("stopwords", sw);
			
		}
		
		Element entries = DomUtils.getChildElementByTagName(element, "entries");
		if (entries != null) {
			List entriesElements = DomUtils.getChildElementsByTagName(entries, "matrixEntry");
			List<MatrixSimilarityEntry> ents = new ArrayList<MatrixSimilarityEntry>(); 
			for (int i = 0; i < entriesElements.size(); ++i) {
				Element childElement = (Element) entriesElements.get(i);
				MatrixSimilarityEntry ent = new MatrixSimilarityEntry();
				ent.setValue1(childElement.getAttribute("val1"));
				ent.setValue2(childElement.getAttribute("val2"));
				ent.setSimilarity(Double.parseDouble(childElement.getAttribute("sim")));
				ents.add(ent);
			}
			beanDefinitionBuilder.addPropertyValue("entries", ents);
		}
		
		return beanDefinitionBuilder.getBeanDefinition();
	}
}
